package com.cobra.util;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.File;

public class ZipUtil {
    /**
     *
     * @param file 源数据
     * @param zipPath   压缩后存放的路径
     * @param isDecrypt 是否需要密码
     * @param password  密码
     * @return
     * @throws Exception
     */
    public static ZipFile zipFile(File file,String zipPath,boolean isDecrypt,String password) throws Exception{
        if(isDecrypt && password == null){
            throw new Exception("未设置密码");
        }
        ZipParameters zipParameters = new ZipParameters();
        ZipFile zipFile = new ZipFile(zipPath);
        // 压缩方式
        zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        // 压缩级别
        zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        //如果需要设置密码则进行如下设置
        if(isDecrypt){
            zipParameters.setEncryptFiles( true );
            zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            zipParameters.setPassword(password);
        }
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File innerFile : files) {
                if(innerFile.isDirectory()){
                    zipFile.addFolder(innerFile.getPath(),zipParameters);
                }else {
                    zipFile.addFile(innerFile,zipParameters);
                }
            }
        }else {
            zipFile.addFile(file,zipParameters);
        }
        return zipFile;
    }
    public static ZipFile zipFile(String path,String zipPath,boolean isDecrypt,String password) throws Exception{
        return zipFile(new File(path),zipPath,isDecrypt,password);
    }

    /**
     *
     * @param zipPath   待解压的文件地址
     * @param upZipPath 解压过后文件存放地址
     * @param isDecrypt 是否需要解密
     * @param password  密码
     * @return
     * @throws Exception
     */
    public static ZipFile unzip(String zipPath,String upZipPath,boolean isDecrypt,String password)throws Exception{
        if(isDecrypt && password == null){
            throw new Exception("未设置密码");
        }
        ZipFile zipFile = new ZipFile(zipPath);
        if(isDecrypt){
            zipFile.setPassword(password);
        }
        zipFile.extractAll(upZipPath);
        return  zipFile;
    }
}
